package mqttclient

import (
	"sync/atomic"

	"go-zero-admin/apps/modules/iot/cmd/link/gateway"
	gatewayConst "go-zero-admin/apps/modules/iot/cmd/link/gateway/constant"
	"go-zero-admin/apps/modules/iot/cmd/link/network"
	networkConst "go-zero-admin/apps/modules/iot/cmd/link/network/constant"
	"go-zero-admin/apps/modules/iot/cmd/link/network/mqttclient"
)

var _ IMqttClientDeviceGateway = (*MqttClientDeviceGateway)(nil)

type (
	IMqttClientDeviceGateway interface {
		gateway.IDeviceGateway
	}

	MqttClientDeviceGateway struct {
		Id                  int64
		MqttClient          mqttclient.IMqttClient
		ProtocolId          int64
		Protocol            string
		Started             atomic.Value
		DeviceGatewayHelper gateway.IDeviceGatewayHelper
	}
)

func (m *MqttClientDeviceGateway) GetId() int64 {
	return m.Id
}

func (m *MqttClientDeviceGateway) GetTransport() *gateway.Transport {
	return new(gateway.Transport).Of(gatewayConst.Mqtt)
}

func (m *MqttClientDeviceGateway) GetNetworkType() *network.NetworkType {
	return new(network.NetworkType).Of(networkConst.MqttClient)
}

func (m *MqttClientDeviceGateway) OnMessage() {
}

func (m *MqttClientDeviceGateway) Startup() error {
	return m.doStart()
}

func (m *MqttClientDeviceGateway) Pause() {
	m.Started.Store(0)
}

func (m *MqttClientDeviceGateway) Shutdown() {
	m.Started.Store(0)
}

func (m *MqttClientDeviceGateway) IsAlive() bool {
	return false
}

func (m *MqttClientDeviceGateway) GetTarget() any {
	return m
}

// 启动网关并订阅主题
func (m *MqttClientDeviceGateway) doStart() error {
	if m.Started.Load() == 0 {
		return nil
	}

	// 订阅主题
	//err := m.MqttClient.SubscribeQos(m.Topics, byte(m.Qos))
	//if err != nil {
	//	return err
	//}

	// 处理接受数据
	//go myNats.NatsApi.SubAsyncQueue(&myNats.NatsHandleEnProperties{
	//	Topic:   networkConst.MqttMsgNatsQue + m.MqttClient.GetId(),
	//	QueName: networkConst.MqttMsgNatsQue + "queue_" + m.MqttClient.GetId(),
	//	QueF: func(msg *nats.Msg) {
	//		mqttMessage := message.Build()
	//		tools.DataTool.UnmarshalDataFromJsonWithGzip(msg.Data, mqttMessage)
	//		fmt.Println(mqttMessage.Payload)
	//	}},
	//)

	return nil
}
